springboot实现文件的上传到项目静态路径下(resource/static)和上传多个文件 您所在的位置:网站首页 〓〓如何将图片文件上传到 staticimagecommon 目录中 springboot实现文件的上传到项目静态路径下(resource/static)和上传多个文件

springboot实现文件的上传到项目静态路径下(resource/static)和上传多个文件

2023-08-11 10:46| 来源: 网络整理| 查看: 265

springboot上传单个文件

上传文件到两个不同的路径下,一个是项目路径,一个的项目编译路径,上传到编译路径下(target)文件可能会自动消失

@PostMapping("/uploadfile") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) throws IOException { //如果文件不存在上传失败 if (file.isEmpty()) { LOGGER.info("上传失败"); System.out.println("文件不存在"); return "upload fail"; } //获取文件名字 String fileName = file.getOriginalFilename(); //设置编译后文件存在路径 String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/images/tx/"; //获取项目路径 File directory = new File("src/main/resources/static/images/tx"); String paths = directory.getCanonicalPath(); File dest = new File(paths+'/' + fileName); System.out.println(dest.getAbsoluteFile()); FileInputStream fileInputStream = (FileInputStream) file.getInputStream(); //以流的方式上传 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName)); byte[] bs = new byte[1024]; int len; while ((len = fileInputStream.read(bs)) != -1) { bos.write(bs, 0, len); } bos.flush(); bos.close(); try { //文件上传 file.transferTo(dest); LOGGER.info("上传成功"); return "upload success"; } catch (IOException e) { LOGGER.error(e.toString(), e); } return "upload success"; } springboot上传多个文件

上传到项目静态路径下可参考上面

@PostMapping("/uploadfiles") @ResponseBody public String upalb(@RequestParam("file") MultipartFile[] file) throws IOException { if(file.length==0){ return "file not exist"; } //分别上传每个文件 for(int i=0;i file[i].transferTo(dest); } catch (IOException e) { e.printStackTrace(); } } return "upload success"; }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有